/** 
 * @Title:  UserAllInfoFragment.java 
 * @author:  Abtswiath丶lxy
 * @data:  2016年6月14日 上午10:45:06 <创建时间>
 * 
 * @history：<以下是历史记录>
 *
 * @modifier: <修改人>
 * @modify date: 2016年6月14日 上午10:45:06 <修改时间>
 * @log: <修改内容>
 *
 * @modifier: <修改人>
 * @modify date: 2016年6月14日 上午10:45:06 <修改时间>
 * @log: <修改内容>
 */
package com.sunmi.usercenter.ui.activity.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.sunmi.usercenter.Constant;
import com.sunmi.usercenter.R;
import com.sunmi.usercenter.bean.Addr;
import com.sunmi.usercenter.bean.Address;
import com.sunmi.usercenter.bean.FmInfo;
import com.sunmi.usercenter.bean.Result;
import com.sunmi.usercenter.bean.Shop;
import com.sunmi.usercenter.bean.ShopType;
import com.sunmi.usercenter.bean.rpc.ReqGetUserInfo;
import com.sunmi.usercenter.bean.rpc.ReqUpdateShopAddress;
import com.sunmi.usercenter.bean.rpc.ReqUpdateShopName;
import com.sunmi.usercenter.bean.rpc.ReqUpdateShopType;
import com.sunmi.usercenter.bean.rpc.ReqUpdateShopUserName;
import com.sunmi.usercenter.utils.CharUtils;
import com.sunmi.usercenter.utils.LogUtil;
import com.sunmi.usercenter.utils.Validator;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.List;

import sunmi.sunmiui.dialog.DialogCreater;
import sunmi.sunmiui.dialog.EditTextDialog;
import sunmi.sunmiui.dialog.ListDialog;
import sunmi.sunmiui.dialog.LoadingDialog;

/**
 * TODO<请描述这个类是干什么的>
 * 
 * @author Abtswiath丶lxy
 * @versionCode 1 <每次修改提交前+1>
 */
public class UserAllInfoFragment extends SuperFragment implements OnClickListener {

	private View mView;
	private RelativeLayout mRelNowAccount, mRelShopType, mRelShopName, mRelShopUserName, mRelShopAddress;
	private TextView mTxtPhone, mTxtShopType, mTxtShopName, mTxtShopUserName, mTxtShopAddress;
	private ImageView mImgLoading;
	private Shop shop;
	private Animation operatingAnim;
	private RelativeLayout mRelBack;
	/**
	 * 修改店铺名字的dialog
	 */
	private EditTextDialog mEditTextDialog4UpdateShopName;
	/**
	 * 加载中店铺类型
	 */
	private LoadingDialog mLoadingDialog;
	/**
	 * 修改店铺联系人名字的dialog
	 */
	private EditTextDialog mEditTextDialog;
	/**
	 * 店铺类型的listdialog
	 */
	private ListDialog mListDialog;
	/**
	 * 修改店铺地址的dialog
	 */
	private EditTextDialog mEditTextDialog4UpdateShopAddress;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		return mView = inflater.inflate(R.layout.fragment_user_center, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		verifyLogin();
		initView();
		fillData();
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		if(!hidden){
			Constant.CLASS_FRAGMENT = Constant.DoubleClickExit;
		}
	}

	private void verifyLogin(){
		shop = mCaCheModel.getShop();
		if(shop==null){
			openFM(new FmInfo(LoginFragment.class, null));
			onDestroy();
		}
	}

	/**
	 * 填充数据
	 */
	private void fillData() {
		shop = mCaCheModel.getShop();
		if (shop != null) {
			String userName = shop.getUserName();
			if(Validator.isEmail(userName)){
				String string = "";
				for (int i = 0; i < (userName.split("@")[0].length()-3); i++) {
					string = string+"*";
				}
				mTxtPhone.setText(userName.substring(0,3) +string +"@" + userName.split("@")[1]);
			}else{
				mTxtPhone.setText(userName.substring(0,3) + "*****" + userName.substring(8, userName.length()));
			}
		}
		if (CharUtils.isEmpty(shop.getContactName())) {
			mTxtShopUserName.setText(getString(R.string.not_filled));
		}else{
			mTxtShopUserName.setText(shop.getContactName());
		}
		if (CharUtils.isEmpty(shop.getShopAddress())) {
			mTxtShopAddress.setText(getString(R.string.not_filled));
//			Toast.makeText(getActivity(),"开始调用定位！",Toast.LENGTH_SHORT).show();
			Intent intent = new Intent();
			intent.setAction("sunmi.systemapi.location");
			intent.setPackage("woyou.system.api");
			getActivity().startService(intent);
		}else{
			mTxtShopAddress.setText(shop.getShopAddress());
		}
		if (CharUtils.isEmpty(shop.getShopType())) {
			mTxtShopType.setText(getString(R.string.not_filled));
		}else{
			mTxtShopType.setText(shop.getShopType());
		}
		if (CharUtils.isEmpty(shop.getShopName())) {
			mTxtShopName.setText(getString(R.string.not_filled));
		}else{
			mTxtShopName.setText(shop.getShopName());
		}
	}
	
	/**
	 * 初始化
	 */
	private void initView() {
		Constant.CLASS_FRAGMENT = Constant.DoubleClickExit;
		mActivity.SetStatusColorFE542B();
		mRelBack = (RelativeLayout) mView.findViewById(R.id.back);
		mRelNowAccount = (RelativeLayout) mView.findViewById(R.id.rel_now_account);
		mRelShopType = (RelativeLayout) mView.findViewById(R.id.lin_shop_type);
		mRelShopName = (RelativeLayout) mView.findViewById(R.id.lin_shop_name);
		mRelShopUserName = (RelativeLayout) mView.findViewById(R.id.lin_shop_username);
		mRelShopAddress = (RelativeLayout) mView.findViewById(R.id.lin_shop_address);
		mTxtPhone = (TextView) mView.findViewById(R.id.txt_phone_hidi);
		mTxtShopType = (TextView) mView.findViewById(R.id.txt_shop_type);
		mTxtShopName = (TextView) mView.findViewById(R.id.txt_shop_name);
		mTxtShopUserName = (TextView) mView.findViewById(R.id.txt_shop_user_name);
		mTxtShopAddress = (TextView) mView.findViewById(R.id.txt_shop_address);
		mImgLoading = (ImageView) mView.findViewById(R.id.img_loading);
		operatingAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.check_anim);  
		LinearInterpolator lin = new LinearInterpolator();
		IntentFilter filter = new IntentFilter(Constant.ACTION_LOCATION_RESULT);
		getActivity().registerReceiver(locationBroadcastReceiver, filter);
		operatingAnim.setInterpolator(lin);
		mImgLoading.setVisibility(View.GONE);
		mRelNowAccount.setOnClickListener(this);
		mRelShopType.setOnClickListener(this);
		mRelShopName.setOnClickListener(this);
		mRelShopUserName.setOnClickListener(this);
		mRelShopAddress.setOnClickListener(this);
		mRelBack.setVisibility(View.GONE);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if(locationBroadcastReceiver!=null){
			getActivity().unregisterReceiver(locationBroadcastReceiver);
		}
	}

	/**
	 * 弹出修改店铺类型的dialog
	 */
	private void updateShopType(){
		mLoadingDialog = DialogCreater.createLoadingDialog(getActivity(),getString(R.string.get_shop_type));
		mLoadingDialog.setCancelable(true);
		mLoadingDialog.setCanceledOnTouchOutside(false);
		mLoadingDialog.show();
		mHttpController.getAllShopType(new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				String json = new String(arg2);
				Gson gson = new Gson();
				Type type = new TypeToken<Result<List<ShopType>>>(){}.getType();
				Result<List<ShopType>> result = null;
				try {
					result = gson.fromJson(json,type);
				}catch (Exception e){
					e.printStackTrace();
				}
				if(result!=null&&result.code==1&&result.data!=null){
					List<ShopType> list = result.data;
					if(list!=null&&list.size()>0){
						mLoadingDialog.dismiss();
						updateShopTypeDialog(list);
					}
				}else{
					showToast(getString(R.string.get_error));
					mLoadingDialog.dismiss();
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				showToast(getString(R.string.get_error));
				mLoadingDialog.dismiss();
			}
		});
	}

	/**
	 * 请求修改店铺类型
	 */
	private void updateShopTypeDialog(final List<ShopType> list){
		String[] arr = new String[list.size()];
		for (int i=0;i<list.size();i++){
			arr[i] = list.get(i).getShopType();
		}
		mListDialog = DialogCreater.createListDialog(getActivity(),getString(R.string.your_shop_type),getString(R.string.cancel),arr);
		mListDialog.setItemClickListener(new ListDialog.ItemClickListener() {
			@Override
			public void OnItemClick(int i) {
				ReqUpdateShopType reqUpdateShopType = new ReqUpdateShopType();
				reqUpdateShopType.settId(list.get(i).gettId());
				reqUpdateShopType.setuId(shop.getuId());
				mHttpController.updateShopType(reqUpdateShopType, asyncHttpResponseHandler);
			}
		});
		mListDialog.show();
	}

	/**
	 * 更新店铺联系人名字
	 */
	private void updateShopUserName(){
		mEditTextDialog = DialogCreater.createEditTextDialog(getActivity(), getString(R.string.cancel), getString(R.string.save), getString(R.string.please_input_shop_username), new OnClickListener() {
			@Override
			public void onClick(View v) {
				mEditTextDialog.dismiss();
				mEditTextDialog = null;
			}
		}, new OnClickListener() {
			@Override
			public void onClick(View v) {
				String msg = mEditTextDialog.getText().trim();
				if(msg.equals(shop.getContactName())){
					mEditTextDialog.dismiss();
					mEditTextDialog = null;
					return;
				}
				if(!CharUtils.isEmpty(msg)){
					ReqUpdateShopUserName reqUpdateShopUserName = new ReqUpdateShopUserName();
					reqUpdateShopUserName.setContactName(msg);
					reqUpdateShopUserName.setuId(shop.getuId());
					mHttpController.updateShopUserName(reqUpdateShopUserName,asyncHttpResponseHandler);
				}else{
					showToast(getString(R.string.input_dont_null));
				}
			}
		});
		mEditTextDialog.setText(shop.getContactName());
		mEditTextDialog.show();
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				if(mEditTextDialog!=null) {
					mEditTextDialog.showSoftInput();
				}
			}
		}, 998);
	}

	/**
	 * 更新店铺地址
	 */
	private void updateShopAddress(){
		mEditTextDialog4UpdateShopAddress = DialogCreater.createEditTextDialog(getActivity(),getString(R.string.cancel),getString(R.string.save),getString(R.string.please_input_shop_address), new OnClickListener() {
					@Override
					public void onClick(View v) {
						mEditTextDialog4UpdateShopAddress.dismiss();
						mEditTextDialog4UpdateShopAddress = null;
					}
				}, new OnClickListener() {
					@Override
					public void onClick(View v) {
						String msg = mEditTextDialog4UpdateShopAddress.getText();
						if(msg.equals(shop.getShopAddress())){
							mEditTextDialog4UpdateShopAddress.dismiss();
							mEditTextDialog4UpdateShopAddress = null;
							return;
						}
						if(!CharUtils.isEmpty(msg)){
							ReqUpdateShopAddress reqUpdateShopAddress = new ReqUpdateShopAddress();
							reqUpdateShopAddress.setShopAddress(msg);
							reqUpdateShopAddress.setuId(shop.getuId());
							mHttpController.updateShopAddress(reqUpdateShopAddress,asyncHttpResponseHandler);

						}else{
							showToast(getString(R.string.input_dont_null));
						}
					}
				});
		mEditTextDialog4UpdateShopAddress.setText(shop.getShopAddress());
		mEditTextDialog4UpdateShopAddress.show();
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				if(mEditTextDialog4UpdateShopAddress!=null) {
					mEditTextDialog4UpdateShopAddress.showSoftInput();
				}
			}
		}, 998);
	}

	/**
	 * 解析拉取的数据
	 * @param arg2
     */
	private void analysis(byte[] arg2){
		if(mListDialog!=null){
			mListDialog.dismiss();
			mListDialog = null;
		}
		if(mEditTextDialog!=null){
			mEditTextDialog.dismiss();
			mEditTextDialog = null;
		}
		if(mEditTextDialog4UpdateShopAddress!=null) {
			mEditTextDialog4UpdateShopAddress.dismiss();
			mEditTextDialog4UpdateShopAddress = null;
		}
		if(mEditTextDialog4UpdateShopName!=null) {
			mEditTextDialog4UpdateShopName.dismiss();
			mEditTextDialog4UpdateShopName = null;
		}
		String json = new String(arg2);
		Gson gson = new Gson();
		Result result = gson.fromJson(json, Result.class);
		if(result!=null&&result.code==1){
			showToast(getString(R.string.update_success));
			againPullData();
		}else{
			showToast(getString(R.string.update_error));
		}
	}

	/**
	 * 更新店铺名字
	 */
	private void updateShopName(){
		mEditTextDialog4UpdateShopName = DialogCreater.createEditTextDialog(getActivity(), getString(R.string.cancel), getString(R.string.save), getString(R.string.please_input_shop_name), new OnClickListener() {
			@Override
			public void onClick(View v) {
				mEditTextDialog4UpdateShopName.dismiss();
				mEditTextDialog4UpdateShopName = null;
			}
		}, new OnClickListener() {
			@Override
			public void onClick(View v) {
				String msg = mEditTextDialog4UpdateShopName.getText();
				if(msg.equals(shop.getShopName())){
					mEditTextDialog4UpdateShopName.dismiss();
					mEditTextDialog4UpdateShopName = null;
					return;
				}
				if(!CharUtils.isEmpty(msg)){
					ReqUpdateShopName updateShopName = new ReqUpdateShopName();
					updateShopName.setuId(shop.getuId());
					updateShopName.setShopName(msg);
					mHttpController.updateShopname(updateShopName,asyncHttpResponseHandler);
				}else{
					showToast(getString(R.string.input_dont_null));
				}
			}
		});
		mEditTextDialog4UpdateShopName.setText(shop.getShopName());
		mEditTextDialog4UpdateShopName.show();
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				if(mEditTextDialog4UpdateShopName!=null) {
					mEditTextDialog4UpdateShopName.showSoftInput();
				}
			}
		}, 998);
	}

	
	/**
	 * 重新拉取数据，并且刷新UI
	 */
	private void againPullData(){
		mImgLoading.setVisibility(View.VISIBLE);
		mImgLoading.startAnimation(operatingAnim);
		ReqGetUserInfo reqGetUserInfo = new ReqGetUserInfo();
		reqGetUserInfo.setuId(shop.getuId());
		mHttpController.getUserInfo(reqGetUserInfo, new AsyncHttpResponseHandler() {
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				String json = new String(arg2);
				Gson gson = new Gson();
				Type type = new TypeToken<Result<Shop>>(){}.getType();
				Result<Shop> result = null;
				try {
					result = gson.fromJson(json,type);
				}catch (Exception e){
					e.printStackTrace();
				}
				if(result!=null&&result.getCode()==1&&result.data!=null){
					mImgLoading.clearAnimation();
					mImgLoading.setVisibility(View.GONE);
					result.data.setuId(shop.getuId());
					mCaCheModel.saveShop(result.data);
					fillData();
				}else{
					mImgLoading.clearAnimation();
					mImgLoading.setVisibility(View.GONE);
				}
			}
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				mImgLoading.clearAnimation();
				mImgLoading.setVisibility(View.GONE);
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rel_now_account:
			openFM(new FmInfo(UserAcountFragment.class, null));
			break;
		case R.id.lin_shop_type:
			updateShopType();
			break;
		case R.id.lin_shop_name:
			updateShopName();
			break;
		case R.id.lin_shop_username:
			updateShopUserName();
			break;
		case R.id.lin_shop_address:
			updateShopAddress();
			break;
		default:
			break;
		}
	}

	private AsyncHttpResponseHandler asyncHttpResponseHandler = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			analysis(arg2);
		}
		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
			showToast(getString(R.string.update_error));
			if(mListDialog!=null){
				mListDialog.dismiss();
				mListDialog = null;
			}
			if(mEditTextDialog!=null){
				mEditTextDialog.dismiss();
				mEditTextDialog = null;
			}
			if(mEditTextDialog4UpdateShopAddress!=null) {
				mEditTextDialog4UpdateShopAddress.dismiss();
				mEditTextDialog4UpdateShopAddress = null;
			}
			if(mEditTextDialog4UpdateShopName!=null) {
				mEditTextDialog4UpdateShopName.dismiss();
				mEditTextDialog4UpdateShopName = null;
			}
		}
	};


	private BroadcastReceiver locationBroadcastReceiver = new BroadcastReceiver(){

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (Constant.ACTION_LOCATION_RESULT.equals(action)) {
				String extra = intent.getStringExtra(Constant.LOCATION_RESULT_EXTRA);
				LogUtil.d("??????",extra);
//				Toast.makeText(getActivity(),"接收到定位："+extra,Toast.LENGTH_SHORT).show();
				if(TextUtils.isEmpty(extra))return;
				if(!TextUtils.isEmpty(shop.getShopAddress()))return;
				Gson gson = new Gson();
				Addr address = null;
				try {
					address = gson.fromJson(extra,Addr.class);
				}catch (Exception e){
					e.printStackTrace();
				}
				if(address!=null&&!TextUtils.isEmpty(address.getmAddr().getAddress())){
					ReqUpdateShopAddress reqUpdateShopAddress = new ReqUpdateShopAddress();
					reqUpdateShopAddress.setShopAddress(address.getmAddr().getAddress());
					reqUpdateShopAddress.setuId(shop.getuId());
					mHttpController.updateShopAddress(reqUpdateShopAddress, new AsyncHttpResponseHandler() {
						@Override
						public void onSuccess(int i, Header[] headers, byte[] bytes) {againPullData();}
						@Override
						public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {	}
					});
				}
			}
		}
	};

}
